URL Rewriting in ASP.NET 4.5 and the Web API

We have a long-standing ASP.NET web form application that was born in .NET 1.1 / IIS6. Now we are working on .NET4.5 / IIS7, but we have not done anything with MVC.

We provide a catalog to customers and provide them with a URL that they can use:

www.ourhost.com/customername

Using the custom IHttpModule that we developed, we pull the "username" from the URL to find the client in the database. This client identifier is then stored in the context of the page * and is used by almost all pages of the site to configure content for this client. After this process, the above URL will be rewritten and processed as

www.ourhost.com/index.aspx

with the index index.aspx accessing the client identifier through its context, and he can do his job.

This works great and we support several thousand customers. the rewrite logic is rather complicated because it checks the customer accounts, redirects to the "uh oh" page if the client is invalid, and to the other "find seller" page if the client has not paid, etc. etc.

Now I would like to create some Web API controllers and MVC-style rewriting bothers me. I see many examples when rewriting happens so that the URL is similar to this job:

www.ourhost.com/api/{controller}

but I still need these web avi calls to be made in the context of the client. Our pages are becoming more complex with asynchronous JSON / AJAX calls, but to respond to these calls, I still need the client context. I would like the url to be

www.ourhost.com/customername/api/{controller}

, , , IHttpModule.

?

* UPDATE: " ", HttpContext, -, , , /.

+5
1

, .

API MVC , . , API RESTFul.

, -API MVC, global.asax.cs

    protected void Application_PostAuthorizeRequest()
    {
        // To enable session state in the WebAPI.
        System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
    }

URL- "", , , http . MVC-.

URL, WebApiConfig.cs, :

        config.Routes.MapHttpRoute(
            name: "WithCustomerApi",
            routeTemplate: "api/{customername}/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

ActionFilter API, , /, . MVC

, :

[WebApiAuthentication]
public class BaseApiController : ApiController
{
}

, ( , , ).

public class WebApiAuthenticationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var routeData = actionContext.ControllerContext.Request.GetRouteData();
        var currentContext = HttpContext.Current;

        if (routeData.Route.RouteTemplate.Contains("customername"))
        {
            try
            {
                var authenticated = currentContext.Request.IsAuthenticated;
                if (!authenticated)
                {
                    var customer = routeData.Values["customername"];
                    // do something with customer here and then put into session or cache
                    currentContext.Session.Add("CustomerName", customer);
                }
            }
            catch (Exception exception)
            {
                var error = exception.Message;
                // We dont like the request
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);
            }
        }
        else
        {
            // No customer name specified, send bad request, not found, what have you ... you *could* potentially redirect but we are in API so it probably a service request rather than a user
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.NotFound);
        }

    }
}

-API MVC 5 , , .

, .

[WebApiAuthentication]
public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        var session = HttpContext.Current.Session;

        if (session != null)
        {
            return new string[] {"session is present", "customer is", session["CustomerName"].ToString()};
        }

        return new string[] { "value1", "value2" };
    }

}

, , API, . , ,

+2

All Articles