Encrypt Request/Reponse in MVC4 WebApi

2019-08-01 01:42发布

I have a old api that receives an encrypted request and encrypts the response once complete. I am attempting to switch this to mvc4 webapi and it has gone smooth until I hit this encryption. What I need is a way to decrypt the request when it comes in so mvc will act on it properly. Also once the process is complete encrypt the response before sending it. I do not want to place the encryption parts in each action.

Note: The body is still properly formatted as a single item, so I would push it all through a single action with a selector of my own, but would prefer a more proper rest style implementation.

2条回答
唯我独甜
2楼-- · 2019-08-01 02:27

you can implement your own model binder

public class DecObjModelBinder : IModelBinder
{   


  public object BindModel(ControllerContext controllerContext, 
      ModelBindingContext bindingContext)
   {
    //make a instance of your object
    var myObj = new DecObj()

    //bind the properties from my obj

    myObj.Title= bindingContext
        .ValueProvider
        .GetValue("Title") // The Property name sent from the browser
        .ToString();

    /* then the property you want to decrypt */
    var encBody = bindingContext
        .ValueProvider
        .GetValue("EncBody") // The Property name sent from the browser
        .ToString();

    /* decryption logic here to the encBody then after assign the decrypted value to myObj*/

    return myObj;
   }

and then You register the ModelBinder in Global.asx in Application_Start via: ModelBinders.Binders.Add(typeof(DecObj), new DecObjModelBinder());

查看更多
Summer. ? 凉城
3楼-- · 2019-08-01 02:28

You should be able to do this with a MessageHandler. There are a bunch of examples of how to create MessageHandlers in WebAPIContrib

查看更多
登录 后发表回答