. Net core 1.1.0 MVC controller receives Json strings (JObject object) (1), jsonjobject

Source: Internet
Author: User

. Net core 1.1.0 MVC controller receives Json strings (JObject object) (1), jsonjobject
. Net core 1.1.0 MVC controller receives Json strings (JObject object) (2)

Json is a common data for WEB interactions ,. net core is converted to a strong type, and no corresponding strong type will be discarded. Sometimes we want to obtain the original Json string for processing in the background,.. net core client requests are encapsulated and converted by default. The browser requests get, post, get without sending Json. The Form and Body data methods are used for post sending requests. It is relatively easy to convert the key-value pairs into Json, which is also a Series (1).

First, define your own ModelBinderProvider as follows:

 public class JObjectModelBinderProvider : IModelBinderProvider    {        public IModelBinder GetBinder(ModelBinderProviderContext context)        {            if (context == null) throw new ArgumentNullException(nameof(context));            if (context.Metadata.ModelType == (typeof(JObject)))            {                return new JObjectModelBinder(context.Metadata.ModelType);            }            return null;        }    }

 



Then write the corresponding ModelBinder

 

public class JObjectModelBinder : IModelBinder    {        public JObjectModelBinder(Type type)        {            if (type == null)            {                throw new ArgumentNullException("type");            }        }        public Task BindModelAsync(ModelBindingContext bindingContext)        {            if (bindingContext == null) throw new ArgumentNullException("bindingContext");            ValueProviderResult result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);            try            {                JObject obj = new JObject();                if (bindingContext.ModelType == typeof(JObject))                {                    foreach (var item in bindingContext.ActionContext.HttpContext.Request.Form)                    {                        obj.Add(new JProperty(item.Key.ToString(), item.Value.ToString()));                    }                    if ((obj.Count == 0))                    {                        bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, bindingContext.ModelMetadata.ModelBindingMessageProvider.ValueMustNotBeNullAccessor(result.ToString()));                        return Task.CompletedTask;                    }                    bindingContext.Result = (ModelBindingResult.Success(obj));                    return Task.CompletedTask;                }                return Task.CompletedTask;            }            catch (Exception exception)            {                if (!(exception is FormatException) && (exception.InnerException != null))                {                    exception = ExceptionDispatchInfo.Capture(exception.InnerException).SourceException;                }                bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, exception, bindingContext.ModelMetadata);                return Task.CompletedTask;            }        }    }

 




Add JObjectModelBinderProvider to Startup.
Services. AddMvc (options =>
{
Options. ModelBinderProviders. Insert (0, new JObjectModelBinderProvider (); // bind to JobjectModelBinderProvider
});


Use
[HttpPost]
Public IActionResult ComWizard (JObject data)
{
Return new JsonResult (data );
}
Web end

$. Post ("/Home/ComWizard", {UserName: "Jerry", Password: "123"}, function (data ){
Alert (data. userName + "--" + data. password); // This is submitted in Form key-value pairs, not Json, but is considered as JObject in the Controller
});


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.