相关疑难解决方法(0)

有没有办法强制ASP.NET Web API返回纯文本?

我需要从ASP.NET Web API控制器以纯文本形式获得响应.

我试过做一个请求,Accept: text/plain但它似乎没有做的伎俩.此外,请求是外部的,不受我的控制.我要做的是模仿旧的ASP.NET方式:

context.Response.ContentType = "text/plain";
context.Response.Write("some text);
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

编辑,解决方案:根据Aliostad的回答,我添加了WebAPIContrib文本格式化程序,在Application_Start中初始化它:

  config.Formatters.Add(new PlainTextFormatter());
Run Code Online (Sandbox Code Playgroud)

我的控制器最终结果如下:

[HttpGet, HttpPost]
public HttpResponseMessage GetPlainText()
{
  return ControllerContext.Request.CreateResponse(HttpStatusCode.OK, "Test data", "text/plain");
}
Run Code Online (Sandbox Code Playgroud)

asp.net asp.net-web-api

120
推荐指数
5
解决办法
7万
查看次数

Request.Content.ReadAsMultipartAsync永远不会返回

我有一个使用ASP.NET Web Api编写的系统的API,我试图扩展它以允许上传图像.我已经做了一些谷歌搜索,并找到了如何使用MultpartMemoryStreamProvider和一些异步方法接受文件的推荐方法,但我在ReadAsMultipartAsync上等待永远不会返回.

这是代码:

[HttpPost]
public async Task<HttpResponseMessage> LowResImage(int id)
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    var provider = new MultipartMemoryStreamProvider();

    try
    {
        await Request.Content.ReadAsMultipartAsync(provider);

        foreach (var item in provider.Contents)
        {
            if (item.Headers.ContentDisposition.FileName != null)
            {

            }
        }

        return Request.CreateResponse(HttpStatusCode.OK);
    }
    catch (System.Exception e)
    {
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以一路走到:

await Request.Content.ReadAsMultipartAsync(provider);
Run Code Online (Sandbox Code Playgroud)

它永远不会完成.

我等待永远不会回来的原因是什么?

更新

我试图使用curl POST这个动作,命令如下:

C:\cURL>curl -i -F filedata=@C:\LowResExample.jpg http://localhost:8000/Api/Photos/89/LowResImage
Run Code Online (Sandbox Code Playgroud)

我也尝试使用以下html来POST动作,同样的事情发生:

<form method="POST" action="http://localhost:8000/Api/Photos/89/LowResImage" enctype="multipart/form-data">
    <input type="file" name="fileupload"/>
    <input type="submit" name="submit"/>
</form>
Run Code Online (Sandbox Code Playgroud)

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

54
推荐指数
2
解决办法
3万
查看次数

在Action Filter上获取用户名

我使用Web API的MVC4 Web应用程序.我想创建一个动作过滤器,我想知道哪个用户(登录用户)做了动作.我该怎么做?

public class ModelActionLog : ActionFilterAttribute
{
    public override void OnActionExecuting(SHttpActionContext actionContext)
    {
       string username = ??
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
       ??
    }
}
Run Code Online (Sandbox Code Playgroud)

c# action-filter asp.net-web-api

30
推荐指数
2
解决办法
3万
查看次数

HttpContext.Current在异步Callback中为null

试图访问HttpContext.Current一个方法调用回来,我可以修改一个Session变量,但我收到的异常HttpContext.Currentnull.当_anAgent对象触发它时,异步触发回调方法.

在查看SO上的类似 问题之后,我仍然不确定解决方案.

我的代码的简化版本如下所示:

public partial class Index : System.Web.UI.Page

  protected void Page_Load()
  {
    // aCallback is an Action<string>, triggered when a callback is received
    _anAgent = new WorkAgent(...,
                             aCallback: Callback);
    ...
    HttpContext.Current.Session["str_var"] = _someStrVariable;
  }

  protected void SendData() // Called on button click
  {
    ...
    var some_str_variable = HttpContext.Current.Session["str_var"];

    // The agent sends a message to another server and waits for a call back
    // which triggers …
Run Code Online (Sandbox Code Playgroud)

.net c# asp.net wcf asynchronous

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

在异步任务中使用HttpContext

我有以下mvc动作.

public async Task<JsonResult> DoSomeLongRunningOperation()
{
    return await Task.Run(() =>
    {
        //Do a lot of long running stuff
        //The underlying framework uses the HttpContext.Current.User.Identity.Name so the user is passed on the messagebus.
    }
}
Run Code Online (Sandbox Code Playgroud)

在任务中,HttpContext变为null.我们做了很多尝试,但没有任何事情让我们确信HttpContext总是在我们的新线程中可用.

有没有在异步任务中使用HttpContext的解决方案?

在我们的Io​​cContainer中,我们注册了以下对象,该对象将用户名传递给框架.

public class HttpContextUserIdentityName : ICredentials
{
    public string Name
    {
        get { return HttpContext.Current.User.Identity.Name; }
    }
}
Run Code Online (Sandbox Code Playgroud)

在持久化到数据库之前,在很多地方调用此代码.

我们需要另一种方法来获取用户的用户名启动webrequest或修复HttpContext为null的问题.

因为持久化到数据库发生在任务中,所以在进入任务之前无法访问HttpContext.

我也想不出一个临时持久保存用户名的安全方法,所以我可以实现另一个ICredentials服务对象.

c# asp.net-mvc asynchronous async-await asp.net-mvc-3

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

ASP.NET Web API基本身份验证授权标头

我有一个BasicAuthenticationAttribute检查请求中的Authorization标头但是尽管它存在,它仍然认为Authorization标头为null:

public class BasicAuthenticationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.Request.Headers.Authorization == null)
        {
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
        }

        ...
Run Code Online (Sandbox Code Playgroud)

如果我检查actionContext.Request.Headers我可以看到Authorization列出:

{Connection: Keep-Alive
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-gb
Authorization: REDACTED_BUT_PRESENT==
Host: localhost:44300
Referer: https://localhost:44300/
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; InfoPath.3; .NET4.0E)
}
Run Code Online (Sandbox Code Playgroud)

更新

我刚刚检查了完整的请求标头,它们看起来像这样......我可以看到第一部分中的Authorization标头,但第二部分中的Authorization标头显然为null.

request.Headers

{Connection: Keep-Alive
Accept: …
Run Code Online (Sandbox Code Playgroud)

authorization asp.net-web-api

9
推荐指数
3
解决办法
2万
查看次数

ASP.NET web api - 设置自定义IIdentity或IPrincipal

在我们的asp.net mvc/web api项目中,我们希望使用自定义授权AuthorizeAttribute.我们注意到有两种不同的AuthorizeAttribute,一种是System.Web.MVC用于MVC的System.Net.Http命名空间,另一种是用于web api的命名空间.

它适用于MVC,我们的代码如下:

public class MyPrincipal : IPrincipal
{
    //some custom properties
    public bool IsValid()
    {
        //custom authentication logic
    }

    private IIdentity identity;
    public IIdentity Identity
    {
        get { return this.identity; }
    }

    public bool IsInRole(string role)
    {
        return true;
    }
}

//override AuthorizeCore
public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        MyPrincipal user = new MyPrincipal();

        if (user.isValid())
        {
            httpContext.User = user;
        }
        else
        { …
Run Code Online (Sandbox Code Playgroud)

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

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

带有依赖项注入的HttpContext.Items的WebApi等效项

我正在构建一个ASP.NET WebApi 2.1应用程序,该应用程序需要与HttpContext.Items等效的每个请求缓存。

我什至不能在IIS托管下使用HttpContext,因为在服务/回购层(HttpContext.Current变为异步工作)时,HttpContext似乎丢失了(使用TPL调用,由于某些接口需要匹配,因此不进行异步/等待)空值)。

我使用的是unity 3.5,无法实现按请求进行正确的注入。尝试了HttpControllerActivator方法:

public class HttpControllerActivator : IHttpControllerActivator
{
    private readonly IUnityContainer _container;
    private readonly IHttpControllerActivator _activator;

    public HttpControllerActivator(IUnityContainer container, IHttpControllerActivator activator)
    {
        _container = container;
        _activator = activator;
    }

    public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
    {
        IHttpController controller = _activator.Create(request, controllerDescriptor, controllerType);
        _container.RegisterInstance<System.Net.Http.HttpRequestMessage>(request, new HierarchicalLifetimeManager());

        return controller;

    }
}
Run Code Online (Sandbox Code Playgroud)

但这会将HttpRequestMessage注册在根容器上,而不是在_activator.Create内部由BeginScope()调用创建的子容器上。结果,我在并发负载下得到混合请求实例。

知道如何解决这个问题吗?两天以来我一直在网上搜索,因此没有找到任何真正的解决方案...

unity-container asp.net-web-api

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

将Web API 2与Kentico一起使用时,SiteContext为null

我已经使用Kentico 9 CMS平台实现了Web API 2(通常遵循Kentico的文档),并且整体上它运行良好.但是,在我的控制器中,我发现SiteContext.CurrentSite总是返回null.这是预期的行为还是我做错了什么?

根据本文档,不确定它是否有所作为,但平台在单个域下托管多个站点.所以我的网站运行在以下网址...

  • domain.com/site1
  • domain.com/site2
  • 等等

......并且API在以下路径下可用...

  • domain.com/site1/customapi
  • domain.com/site2/customapi
  • 等等

目前我不得不使用Request对象来提取请求路径并针对Kentico的站点进行检查,SiteProvider以找到当前请求与哪个Kentico站点相关,但是我不会因为API运行而需要该网站的一部分.

我能做些什么来正确连接它吗?仅供参考我注意到它LocalizationContext.CurrentCulture会返回一个CultureInfo物体,所以它并不像我完全脱离了Kentico的背景......

更新解决方案

感谢@ martin-makarsky提供以下答案.用它来创建以下扩展方法,可以从控制器中调用Request.GetCurrentSite()

public static SiteInfo GetCurrentSite(this HttpRequestMessage request)
{
    return SiteInfoProvider.GetRunningSiteInfo(request.RequestUri.Host, System.Web.HttpRuntime.AppDomainAppPath);
}
Run Code Online (Sandbox Code Playgroud)

c# asp.net kentico asp.net-web-api2

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