简体   繁体   English

Asp.net Web Api重定向请求

[英]Asp.net Web Api Redirect request

I have an Asp.net Web API project which has several CRUD methods. 我有一个Asp.net Web API项目,该项目具有几种CRUD方法。

On top of these methods, i want to add an Authorization service that reads the Authorization header and prevent users of accessing the resources (if they are not authorized). 在这些方法之上,我想添加一个授权服务,该服务读取Authorization标头,并防止用户访问资源(如果未授权)。

// Method on internal IP Project
public class InternalController : ApiController
{
    public void Create(CreateRequest request)
    {
        // implement the method
    }
}

// Method on public IP Project
public class ExternalController : ApiController
{
    public async Task Create(CreateRequest request)
    {
        // validate Authorization header and throw exception if not valid

        using (HttpClient client = new HttpClient())
        {
            string parameters = string.Format("param1={0}&param2={1}", request.Param1, request.Param2);

            client.BaseAddress = new Uri("http://192.168.1.1/");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync("api/internal/create?" + parameters);
            response.EnsureSuccessStatusCode();
        }
    }
}

Is there any way of "Redirecting" the request from the External API to the Internal API more easily? 有什么方法可以更轻松地将请求从外部API重定向到内部API?

Right now, i have to manually re-create all the parameters that i receive in ExternalAPI and send them in the InternalAPI, even if they are the same. 现在,我必须手动重新创建我在ExternalAPI中接收的所有参数,并在InternalAPI中发送它们,即使它们相同。

Can i make HttpClient automatically send the HttpRequestMessage (Request) object that i have in ExternalAPI method? 我可以让HttpClient自动发送我在ExternalAPI方法中拥有的HttpRequestMessage (Request)对象吗?

When speaking about ASP.NET Web API . 当谈到ASP.NET Web API时 HttpClient will not automatically redirect you. HttpClient不会自动重定向您。 When you have become response from internal service you can pass it to external. 当您收到内部服务的响应时,可以将其传递给外部。 Or you can redirect your action like here 或者,你可以重定向你的动作就像在这里

To make it correct redirection for client from REST point of view use HTTP Redirect Headers and repsonse codes. 要从REST角度对客户端进行正确的重定向,请使用HTTP重定向标头和响应代码。 For example HTTP response code 302 . 例如HTTP响应代码302 And then client should be able to react on such response code and get redirect address from Location header. 然后,客户端应该能够对此类响应代码做出反应,并从Location标头获取重定向地址。 But it's about redirect for client. 但这是关于客户端的重定向。

When speaking about call of some internal services from your API from architecture . 当谈到从架构调用API中的一些内部服务时 You have following alternatives: 您有以下选择:

  1. Call your internal service as class method 将内部服务称为类方法
  2. Make service to service call 提供服务到服务电话
  3. Setup message queue or bus and your API will communicate with it through service bus. 设置消息队列或总线,您的API将通过服务总线与之通信。

Call your internal service as class method Very easy. 将内部服务称为类方法非常简单。 No impact and delays for service call. 不会影响和延迟服务电话。 But you should reference assembly and it's not always possible. 但是您应该引用汇编,但这并不总是可能的。 Or such way could be not possible due to requirements 否则由于要求可能无法实现

Make service to service call Has disadvantages: your services are tightly coupled, you have delay and should wait for response from internal service. 进行服务到服务的调用有个缺点:服务紧密耦合,有延迟,应等待内部服务的响应。 It's considered as bad practice. 这被认为是不好的做法。 But could be a good temporarily solution as first step to service bus. 但是作为服务总线的第一步,这可能是一个很好的临时解决方案。

Setup message queue or bus and your API will communicate with it through service bus. 设置消息队列或总线,您的API将通过服务总线与之通信。 Your services are decoupled and independent. 您的服务是分离的和独立的。 You shouldn't wait for response. 您不应该等待回应。 But it's technically harder to set up and make your architecture and infrastructure more complex/ 但是从技术上讲,要设置它并使您的架构和基础架构更加复杂/

As summary There is no best way from the box for your architecture and you should select from alternatives based on your requirements. 作为总结 ,对于您的体系结构,没有最好的方法,您应该根据需要从替代方法中进行选择。

Here is the sample code to Post the data to web api:- 这是将数据发布到Web api的示例代码:-

    var handler = new HttpClientHandler {UseDefaultCredentials = true};
        using (var client = new HttpClient(handler))
        {   
            client.BaseAddress = new Uri("https://IE url.com");  
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var  postDataObject = new
                {
                    SCName = properties.Site.PortalName,
                    TotalSites = properties.Web.Webs.Count
     };

    var jsonPostData = new JavaScriptSerializer().Serialize(postDataObject);
                HttpContent content = new StringContent(jsonPostData, System.Text.Encoding.UTF8, "application/json");
                HttpResponseMessage response = client.PostAsync("/controllerclassname/InsertUpdateDataOperation", content).Result;
                if (response.IsSuccessStatusCode)
                {
        //Check the response here
                  //  var webApiResponse = response.Content.ReadAsStringAsync().Result;                    
                }   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET-GET Web请求API - ASP.NET - GET Web Request API ASP.NET Web API 更改请求 URI(重定向到另一种方法) - ASP.NET Web API change request URI (Redirect to another method) ASP.NET Core Web API + Angular 对预检请求的响应未通过访问控制检查:预检请求不允许重定向 - ASP.NET Core Web API + Angular Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request asp.net Web API跟踪-重定向到另一个侦听器 - asp.net web api tracing - redirect to another listener Asp.net为web-api解雇重定向的核心授权 - Asp.net core authorization for web-api firing redirect Asp.net MVC Web API调用重定向到Accountcontroller登录 - Asp.net MVC Web API Call Redirect to Accountcontroller Login ASP.NET Web API:将未经授权的请求重定向到禁止页面 - Asp.net web api : redirect unauthorized requst to forbidden page Identity Server 4 与 ASP.NET 4.6.2 Web API 导致重定向 - Identity Server 4 with ASP.NET 4.6.2 Web API causes redirect 读取ASP.NET WEB API中的每个传入请求(URL) - Reading every incoming request (URL) in ASP.NET WEB API ASP.NET Web Api 2中每个请求的条件依赖性解析 - Conditional dependency resolving per request in ASP.NET Web Api 2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM