标签: asp.net-web-api

Autofac 获取当前身份

我有一个服务,几乎每个方法都需要当前用户执行。在我开始使用 autofac 之前,我基本上创建了一个像这样的公共属性:

private IOrderProvider _orderProvider;

public IOrderProvider OrderProvider => _orderProvider ?? (_orderProvider = new OrderProvider((ClaimsIdentity)User.Identity));
Run Code Online (Sandbox Code Playgroud)

因为这是控制器上的公共属性,所以它可以访问User。现在使用 autofac 我在StartupConfig中注册我的服务。当然,我无权访问那里的用户

有没有办法将当前用户注入到OrderProvider构造函数中,或者有其他方法来获取它?

c# autofac asp.net-web-api

1
推荐指数
1
解决办法
1059
查看次数

请求被中止:无法创建 SSL/TLS 安全通道。| 系统.Net.WebException

我的 webApi 在其中使用第三方 Web api 服务。问题是它在我的本地计算机和 Azure Web 服务中完美运行。但是当我将此解决方案转移到 Azure Vm 实例时,出现此错误。我已经安装了与第 3 方 Web api 相关的正确证书并注册了 HttpClient 并尝试了

ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
Run Code Online (Sandbox Code Playgroud)

但它给出了同样的错误。我不知道确切的错误是什么。有人可以帮忙解决这个问题吗?

c# ssl virtual-machine azure asp.net-web-api

1
推荐指数
1
解决办法
8526
查看次数

时间:2019-03-17 标签:c#webrequestpostimagetowebapi

我在将图像上传到我正在运行的 Web API 时遇到问题。使用 GET 请求时,我可以从 Web API 检索数据,但在处理 POST 请求时遇到问题。我需要将 BMP 图像上传到 Web API,然后发回 json 字符串。

[HttpPost]
public IHttpActionResult TestByte()
{
    Log("TestByte function entered");
    //test to see if i get anything, not sure how to do this
    byte[] data = Request.Content.ReadAsByteArrayAsync().Result;
    byte[] test = Convert.FromBase64String(payload);

    if(test == null || test.Length <= 0)
    {
        Log("No Payload");
        return NotFound();
    }

    if (data == null || data.Length <= 0)
    {
        Log("No payload");
        return NotFound();
    }

    Log("Payload received");
    return Ok();

}
Run Code Online (Sandbox Code Playgroud)

发送图像的 MVC …

c# asp.net-mvc asp.net-web-api

1
推荐指数
1
解决办法
1万
查看次数

Json.Net 反序列化为 C# 派生类

Json.Net没有将其接收到的对象反序列化为我的 Control 类的正确派生类。(请参阅以下对该问题的解释。另请注意,我认为这是解释该问题所需的最少代码量。提前感谢您审阅此问题。)

我正在尝试将以下类序列化为 JSON 或从 JSON 反序列化。

public class Page {
    public Guid Id { get; set; }
    public Guid CustomerId { get; set; }
    public IList<Control> Controls { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是 Control 类:

public class Control : ControlBase
{
    public override Enums.CsControlType CsControlType { get { return Enums.CsControlType.Base; } }
}
Run Code Online (Sandbox Code Playgroud)

这是 ControlBase 抽象类:

public abstract class ControlBase
{
    public Guid Id { get; set; }

    public virtual Enums.CsControlType CsControlType { get; }

    public …
Run Code Online (Sandbox Code Playgroud)

c# serialization json json.net asp.net-web-api

1
推荐指数
1
解决办法
3803
查看次数

ASP.NET Web API 不返回自定义错误信息

我有一个 ASP.NET Web API 2 操作方法:

[System.Web.Http.HttpPost]
public HttpResponseMessage Create(HttpRequestMessage req)
{
   //...

   if (success)
      return Request.CreateResponse(HttpStatusCode.Created);

   return CreateErrorResponse(HttpStatusCode.BadRequest, "you done bad");
}
Run Code Online (Sandbox Code Playgroud)

直到我做了“某事”,一旦出错,它就会返回 http 400,并带有自定义错误文本“you did bad”。这就是预期的结果。

它不再返回自定义文本;它只是返回标准的“错误请求”。一直在试图了解是什么改变导致了这种情况的发生。

所以我尝试:

var response = new { message = "you done bad" };
return Request.CreateResponse(HttpStatusCode.BadRequest, response);
Run Code Online (Sandbox Code Playgroud)

相同的结果。

然后我创建了一个新的、干净的 Web API 项目,并得到了我期望的结果。

我是如何破坏我的项目的?

asp.net asp.net-mvc asp.net-web-api asp.net-web-api2

1
推荐指数
1
解决办法
2841
查看次数

使用正确的键名称添加 ModelState 错误

我有一个简单的模型,例如:

public class Employer 
{
    [Required(ErrorMessage = "Please specify id")]
    public int Id { get; set; }

    [MaxLength(256, ErrorMessage = "Max lenght should be less than 256")]
    [Required(ErrorMessage = "Please specify Name")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Please specify id of organization")]
    public int OrganizationId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

那么控制器是:

public IHttpActionResult Post(Employer employer)
{
    if(!IsActiveOrganization(employer.OrganizationId))
    {
        ModelState.AddModelError(nameof(employer.OrganizationId), "The organization is not active!");
    }
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我正在尝试在创建新雇主之前验证模型。因此,当我传递无效模型时id,响应将如下:

{ …
Run Code Online (Sandbox Code Playgroud)

c# validation asp.net-mvc modelstate asp.net-web-api

1
推荐指数
1
解决办法
3114
查看次数

访问 .NET 控制器中的查询参数

我在 jQuery 中有这个函数

var uri = "api/queries";

function test(){
    var params = {
        origin: $('#depair').val(),
        destination: $('#destair').val(),
        departure_date: $('#depdate').val(),
        currency: $('#currency').val(),
    }
    $.getJSON(uri, params)
        .done(function (data) {
            console.log(data);
    });
}
Run Code Online (Sandbox Code Playgroud)

它将请求发送到此Controller

public class QueriesController : ApiController
{
    [HttpGet]
    public string GetInfo()
    {
        return "blah";
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,请求看起来像这样

http://localhost:55934/api/queries?origin=&destination=&departure_date=&currency=

如何从控制器GetInfo方法内部访问请求的参数?

.net c# asp.net-mvc jquery asp.net-web-api

1
推荐指数
1
解决办法
1万
查看次数

在 WebApi Core ActionFilter 中获取请求正文作为字符串?

以下是我在WebApi .Net Core 2项目中的ActionFilter:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class RequestLoggingAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext actionContext)
    {
        var request = actionContext.HttpContext.Request;
        var route = request.Path.HasValue ? request.Path.Value : "";
        var requestHeader = request.Headers.Aggregate("", (current, header) => current + $"{header.Key}: {header.Value}{Environment.NewLine}");
        request.EnableRewind();
        var requestBody = new StreamReader(request.Body).ReadToEnd();
    }
}
Run Code Online (Sandbox Code Playgroud)

requestHeader具有正确的值并且可以,但requestBody始终为空。
我通过将带有以下正文的请求发送到操作来测试它。

[
 {
  "TrackingCode": "96003445",
  "Description": "",
  "InnerMessage": "",
  "Status": 11
 },
 {
  "TrackingCode": "96003840",
  "Description": "",
  "InnerMessage": "Inner message",
  "Status": 11
 }
]
Run Code Online (Sandbox Code Playgroud)

如何在 WebApi …

asp.net-web-api asp.net-core asp.net-core-webapi .net-core-2.0

1
推荐指数
1
解决办法
5595
查看次数

将实体集动态添加到 ODataConventionModelBuilder 或 ODataModelBuilder

有没有办法将 EntitySet 动态添加到 ODataConventionModelBuilder。

我正在 .net 中开发 OData 服务。我们将返回的一些实体来自外部程序集。我很好地阅读了程序集并获取了相关类型,但由于这些类型是变量,我不确定如何将它们定义为实体集。

例子:

    public static void Register(HttpConfiguration config)
    {
        //some config house keeping here

        config.MapODataServiceRoute("odata", null, GetEdmModel(), new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer));

        //more config housekeeping
    }

    private static IEdmModel GetEdmModel()
    {
        ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
        builder.Namespace = "SomeService";
        builder.ContainerName = "DefaultContainer";

        //These are the easy, available, in-house types
        builder.EntitySet<Dog>("Dogs"); 
        builder.EntitySet<Cat>("Cats");
        builder.EntitySet<Horse>("Horses"); 

        // Schema manager gets the rest of the relevant types from reading an assembly.  I have them, now I just need to create entity …
Run Code Online (Sandbox Code Playgroud)

odata asp.net-web-api

1
推荐指数
1
解决办法
1706
查看次数

Web API post 数组但 frombody 始终为 null

我有以下格式的数组,我需要将其发布到 API:

console.log(addserverList);

大批

我想将其传递给 api 的 post 方法

   const options = {headers: {'Content-Type': 'application/json'}};
            return this.http.post(           'http://localhost:54721/api/BulkUpload/SaveBulkUploadData',addserverList,options)
Run Code Online (Sandbox Code Playgroud)

我可以发布到 api,但数据传递始终显示为 NULL

空值

模型 i 的结构如下:

模型

生成数组的函数

private extractData(res: Response) {

        let csvData = res['_body'] || '';
        let allTextLines = csvData.split(/\r\n|\n/);
        let headers = allTextLines[0].split(',');
        let lines = [];

        for ( let i = 0; i < allTextLines.length; i++) {
            // split content based on comma
            let data = allTextLines[i].split(',');
            if (data.length == headers.length) {
                let tarr = [];
                for ( let j …
Run Code Online (Sandbox Code Playgroud)

.net c# asp.net-web-api asp.net-web-api2 angular

1
推荐指数
1
解决办法
3631
查看次数