首页 \ 问答 \ 使用.NET Core自托管Web API时出现问题(Trouble with self-hosting web API with .NET Core)

使用.NET Core自托管Web API时出现问题(Trouble with self-hosting web API with .NET Core)

我在.NET Core中自我托管我的Web API时遇到了问题。 它在IIS上运行良好,但当我尝试自我托管时,我得到了身份验证错误。 我试图在其他解决方案中使用cookie身份验证,但徒劳无功。 我现在只有一条路线,但是在放置了多个断点后,我发现它甚至没有到达我的控制器的构造器。 如果有人能给我一个解决方案的提示,我将不胜感激:)

这里是我的代码的片段。

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseApplicationInsightsRequestTelemetry();

    app.UseApplicationInsightsExceptionTelemetry();

    app.UseMvc();
}

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(this.Configuration);

    // Add the database used
    services.AddDbContext<VaultContext>(options => options.UseSqlServer(this.Configuration.GetConnectionString("VaultDatabase")));

    // Add our repository type
    services.AddScoped<VaultRepository, VaultRepository>();
    services.AddScoped<UserResolverService, UserResolverService>();
    services.AddScoped<PersonalizationServiceClient, PersonalizationServiceClient>();
    services.AddScoped<PersistenceToDataModelConverter, PersistenceToDataModelConverter>();

    services.AddMvc(config =>
    {
        var policy = new AuthorizationPolicyBuilder()
                            .RequireAuthenticatedUser()
                            .Build();
        config.Filters.Add(new AuthorizeFilter(policy));
    });
}

''services.AddMvc''中的配置lamda是我发现的唯一有效的,它强制调用者提供他的Windows凭据,我稍后将根据他的个人资料分析和显示信息。 如果这不是正确的方法,请告诉我。

和我的控制器类

public VaultController(VaultRepository repository, UserResolverService currentuser, PersonalizationServiceClient personalizationService, PersistenceToDataModelConverter persistenceToDataModelConverter)
{
    this.repository = repository;
    this.currentuser = currentuser;
    this.personalizationService = personalizationService;
    this.persistenceToDataModelConverter = persistenceToDataModelConverter;
}

/// <summary>
/// The get profile.
/// </summary>
/// <returns>
/// The <see cref="IActionResult"/>.
/// </returns>
[HttpGet]
[Route("/Profile")]
[Produces(typeof(UserProfile))]
public IActionResult SearchProfile()
{
    try
    {
        if (!this.currentuser.IsAuthenticated)
        {
            throw new Exception("This service does not support anonymous calls.");
        }

        var profile = Task.Run(() => this.personalizationService.GetUserProfileAsync(this.currentuser.GetCurrentWindowsIdentityName)).Result;

        var userProfile = this.persistenceToDataModelConverter.Convert(profile);
        userProfile.UserAdLogin = this.currentuser.GetCurrentWindowsIdentityName;

        return this.Ok(userProfile);
    }
    catch (Exception ex)
    {
        return this.NotFound(ex);
    }
}

这是我得到的错误

在这里输入图像描述


i am having trouble with self-hosting my web API in .NET Core. It runs fine on IIS but i get Authentication errors when im trying to self-host. I tried using cookie authentication among other solutions but in vain. I have only 1 route for now but after putting multiple breakpoints i noticed that it doesnt even reach the constructor of my controlelr. If anyone could give me a hint of a solution i would greatly appreciate it :)

Here are snippets of my code.

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseApplicationInsightsRequestTelemetry();

    app.UseApplicationInsightsExceptionTelemetry();

    app.UseMvc();
}

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(this.Configuration);

    // Add the database used
    services.AddDbContext<VaultContext>(options => options.UseSqlServer(this.Configuration.GetConnectionString("VaultDatabase")));

    // Add our repository type
    services.AddScoped<VaultRepository, VaultRepository>();
    services.AddScoped<UserResolverService, UserResolverService>();
    services.AddScoped<PersonalizationServiceClient, PersonalizationServiceClient>();
    services.AddScoped<PersistenceToDataModelConverter, PersistenceToDataModelConverter>();

    services.AddMvc(config =>
    {
        var policy = new AuthorizationPolicyBuilder()
                            .RequireAuthenticatedUser()
                            .Build();
        config.Filters.Add(new AuthorizeFilter(policy));
    });
}

The config lamda in the ''services.AddMvc'' is the only i found that worked that forced the caller to give his Windows credentials that i will later analyze and display information based on his profile. If this is not the right way to do it please tell me.

And my controller class

public VaultController(VaultRepository repository, UserResolverService currentuser, PersonalizationServiceClient personalizationService, PersistenceToDataModelConverter persistenceToDataModelConverter)
{
    this.repository = repository;
    this.currentuser = currentuser;
    this.personalizationService = personalizationService;
    this.persistenceToDataModelConverter = persistenceToDataModelConverter;
}

/// <summary>
/// The get profile.
/// </summary>
/// <returns>
/// The <see cref="IActionResult"/>.
/// </returns>
[HttpGet]
[Route("/Profile")]
[Produces(typeof(UserProfile))]
public IActionResult SearchProfile()
{
    try
    {
        if (!this.currentuser.IsAuthenticated)
        {
            throw new Exception("This service does not support anonymous calls.");
        }

        var profile = Task.Run(() => this.personalizationService.GetUserProfileAsync(this.currentuser.GetCurrentWindowsIdentityName)).Result;

        var userProfile = this.persistenceToDataModelConverter.Convert(profile);
        userProfile.UserAdLogin = this.currentuser.GetCurrentWindowsIdentityName;

        return this.Ok(userProfile);
    }
    catch (Exception ex)
    {
        return this.NotFound(ex);
    }
}

Here is the error i get

enter image description here


原文:https://stackoverflow.com/questions/39754306
更新时间:2022-08-22 14:08

最满意答案

在添加asm volatile("": "+m"(a), "+m"(b), "+m"(c)::"memory");main的结尾处,我的gcc副本发出这样的结果:

400610:       48 81 ec 08 60 00 00    sub    $0x6008,%rsp
400617:       ba 00 20 00 00          mov    $0x2000,%edx
40061c:       31 f6                   xor    %esi,%esi
40061e:       48 8d bc 24 00 20 00    lea    0x2000(%rsp),%rdi
400625:       00
400626:       e8 b5 ff ff ff          callq  4005e0 <memset@plt>
40062b:       ba 00 20 00 00          mov    $0x2000,%edx
400630:       31 f6                   xor    %esi,%esi
400632:       48 8d bc 24 00 40 00    lea    0x4000(%rsp),%rdi
400639:       00
40063a:       e8 a1 ff ff ff          callq  4005e0 <memset@plt>
40063f:       31 c0                   xor    %eax,%eax
400641:       0f 1f 80 00 00 00 00    nopl   0x0(%rax)
400648:       c5 f9 6f 84 04 00 20    vmovdqa 0x2000(%rsp,%rax,1),%xmm0
40064f:       00 00
400651:       c5 f9 fe 84 04 00 40    vpaddd 0x4000(%rsp,%rax,1),%xmm0,%xmm0
400658:       00 00
40065a:       c5 f8 29 04 04          vmovaps %xmm0,(%rsp,%rax,1)
40065f:       48 83 c0 10             add    $0x10,%rax
400663:       48 3d 00 20 00 00       cmp    $0x2000,%rax
400669:       75 dd                   jne    400648 <main+0x38>

所以它认识到,第一个循环只是对一对数组进行memset ,第二个循环做了一个向量加法,并对其进行了适当的矢量化。

我使用gcc version 4.9.0 20140521 (prerelease) (GCC)

一台使用gcc version 4.7.2 (Debian 4.7.2-5)的老机器也以循环方式gcc version 4.7.2 (Debian 4.7.2-5)循环,但方式不同。 您的-ftree-vectorizer-verbose=2设置使其发出以下输出:

Analyzing loop at foo155.cc:10


Vectorizing loop at foo155.cc:10

10: LOOP VECTORIZED.
foo155.cc:1: note: vectorized 1 loops in function.

你可能会欺骗你的编译器标志(我使用g++ -O3 -ftree-vectorize -ftree-vectorizer-verbose=2 -march=native foo155.cc -o foo155来构建)或者有一个非常旧的编译器。


For what it's worth, after adding an asm volatile("": "+m"(a), "+m"(b), "+m"(c)::"memory"); near the end of main, my copy of gcc emits this:

400610:       48 81 ec 08 60 00 00    sub    $0x6008,%rsp
400617:       ba 00 20 00 00          mov    $0x2000,%edx
40061c:       31 f6                   xor    %esi,%esi
40061e:       48 8d bc 24 00 20 00    lea    0x2000(%rsp),%rdi
400625:       00
400626:       e8 b5 ff ff ff          callq  4005e0 <memset@plt>
40062b:       ba 00 20 00 00          mov    $0x2000,%edx
400630:       31 f6                   xor    %esi,%esi
400632:       48 8d bc 24 00 40 00    lea    0x4000(%rsp),%rdi
400639:       00
40063a:       e8 a1 ff ff ff          callq  4005e0 <memset@plt>
40063f:       31 c0                   xor    %eax,%eax
400641:       0f 1f 80 00 00 00 00    nopl   0x0(%rax)
400648:       c5 f9 6f 84 04 00 20    vmovdqa 0x2000(%rsp,%rax,1),%xmm0
40064f:       00 00
400651:       c5 f9 fe 84 04 00 40    vpaddd 0x4000(%rsp,%rax,1),%xmm0,%xmm0
400658:       00 00
40065a:       c5 f8 29 04 04          vmovaps %xmm0,(%rsp,%rax,1)
40065f:       48 83 c0 10             add    $0x10,%rax
400663:       48 3d 00 20 00 00       cmp    $0x2000,%rax
400669:       75 dd                   jne    400648 <main+0x38>

So it recognised that the first loop was just doing memset to a couple arrays and the second loop was doing a vector addition, which it appropriately vectorised.

I'm using gcc version 4.9.0 20140521 (prerelease) (GCC).

An older machine with gcc version 4.7.2 (Debian 4.7.2-5) also vectorises the loop, but in a different way. Your -ftree-vectorizer-verbose=2 setting makes it emit the following output:

Analyzing loop at foo155.cc:10


Vectorizing loop at foo155.cc:10

10: LOOP VECTORIZED.
foo155.cc:1: note: vectorized 1 loops in function.

You probably goofed your compiler flags (I used g++ -O3 -ftree-vectorize -ftree-vectorizer-verbose=2 -march=native foo155.cc -o foo155 to build) or have a really old compiler.

相关问答

更多
  • 许多CPU具有“向量”或“SIMD”指令集,它们同时对两个,四个或更多个数据应用相同的操作。 现代x86芯片具有SSE指令,许多PPC芯片都具有“Altivec”指令,甚至一些ARM芯片也有一个称为NEON的向量指令集。 “向量化”(简化)是重写循环的过程,因此,不是像数组中的单个元素N次处理一样,它会同时处理(例如)4个数组元素的N / 4次。 (我选择了4,因为现代硬件最有可能直接支持;术语“向量化”也用于描述一个更高级别的软件转换,您可以在其中简单地抽象出循环,只需描述对数组而不是元素的操作组成它们) ...
  • 不,不能保证。 我可以找到OpenMP 4.5标准的相关部分(重点介绍): (1.3)当任何线程遇到simd构造时, 可以使用线程可用的SIMD通道同时执行与构造相关的循环迭代。 (2.8.1)simd结构可以应用于一个循环,以指示该循环可以转换为一个SIMD循环(也就是说,可以使用SIMD指令同时执行循环的多次迭代)。 (附录C)在任何给定时间并发执行的迭代次数是实现定义的。 (1.2.7)实现定义:必须由实现记录的行为,并允许在不同的兼容实现中有所不同。 允许实现将此行为定义为未指定。 No, it i ...
  • 你基本上是在卷积,对边界进行了一些特殊的处理。 尝试以下操作: from scipy.signal import convolve2d # define your filter f = np.array([[0.0, 0.2, 0.0], [0.2,-0.8, 0.2], [0.0, 0.2, 0.0]]) # select parts of 'a' to be used for convolution b = (a * (a > 3))[1:- ...
  • 你可以使用movsum而不是你的循环: ref1 = movsum(vec(T+3:T+2*n+2),n+1,'Endpoints','discard'); You can use movsum instead of your loop: ref1 = movsum(vec(T+3:T+2*n+2),n+1,'Endpoints','discard');
  • 我稍微修改了你的源代码,以确保GCC无法删除循环: #include #define n 1024 int main () { int i, a[n], b[n], c[n]; for(i=0; i
  • 在添加asm volatile("": "+m"(a), "+m"(b), "+m"(c)::"memory"); 在main的结尾处,我的gcc副本发出这样的结果: 400610: 48 81 ec 08 60 00 00 sub $0x6008,%rsp 400617: ba 00 20 00 00 mov $0x2000,%edx 40061c: 31 f6 xor %esi,%esi 4 ...
  • 从http://research.microsoft.com/en-us/um/people/simonpj/papers/ndp/haskell-beats-C.pdf中的工作中得到GHC的SIMD分支, 网址为https://ghc.haskell .org / trac / ghc / wiki / SIMD以及正在进行的工作,将这些指令作为原始版本,适用于诸如vector的库。 ( https://dorchard.wordpress.com/2013/10/14/automatic-simd-ve ...
  • 你已经腌制了矢量化数组,而不是变换器,你需要pickle.dump(tfidf_vectorizer, idxf, pickle.HIGHEST_PROTOCOL) You've pickled the vectorized array, not the transformer, you need pickle.dump(tfidf_vectorizer, idxf, pickle.HIGHEST_PROTOCOL)
  • 我还没有看到GCC或英特尔C ++自动向量化任何东西,但非常简单的循环,即使给定的算法代码可以(并且在我使用SSE内在函数手动重写之后)被矢量化。 其中一部分是保守的 - 特别是当遇到可能的指针别名时,C / C ++编译器很难向自己“证明”矢量化是安全的,即使你是程序员知道的那样。 大多数编译器(明智地)更喜欢不优化代码而不是冒错误编译它的风险。 这是高级语言比C更有优势的一个领域,至少在理论上是这样的(我在理论上说,因为我实际上并不知道任何自动向量化的ML或Haskell编译器)。 它的另一部分只是分析 ...
  • 以一般的方式,我认为差异实际上是吞吐量(延迟)与操作的数量(复杂性)。 如果你要为你构建一个非常专用的ASIC算法,你将不得不进行n ^ 3次操作。 通过向量化,您可以说这些操作中的一些可以彼此独立地并行执行。 Matlab和当前的处理器更加聪明,可以在“并行”中进行某些操作,例如64位处理器可以进行2到32位的4-16bit等式的总和。 想想O(n ^ 3)中的两种算法,其中每个操作必须完全独立完成(你可以对这个算法进行矢量化),另外两个算法必须是系列的(你不能对它进行矢量化)。 每个特殊硬件都需要n ^ ...

相关文章

更多

最新问答

更多
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)
  • 是否可以嵌套hazelcast IMaps?(Is it possible to nest hazelcast IMaps? And whick side effects can I expect? Is it a good Idea anyway?)
  • UIViewAnimationOptionRepeat在两个动画之间暂停(UIViewAnimationOptionRepeat pausing in between two animations)
  • 在x-kendo-template中使用Razor查询(Using Razor query within x-kendo-template)
  • 在BeautifulSoup中替换文本而不转义(Replace text without escaping in BeautifulSoup)
  • 如何在存根或模拟不存在的方法时配置Rspec以引发错误?(How can I configure Rspec to raise error when stubbing or mocking non-existing methods?)
  • asp用javascript(asp with javascript)
  • “%()s”在sql查询中的含义是什么?(What does “%()s” means in sql query?)
  • 如何为其编辑的内容提供自定义UITableViewCell上下文?(How to give a custom UITableViewCell context of what it is editing?)
  • c ++十进制到二进制,然后使用操作,然后回到十进制(c++ Decimal to binary, then use operation, then back to decimal)
  • 以编程方式创建视频?(Create videos programmatically?)
  • 无法在BeautifulSoup中正确解析数据(Unable to parse data correctly in BeautifulSoup)
  • webform和mvc的区别 知乎
  • 如何使用wadl2java生成REST服务模板,其中POST / PUT方法具有参数?(How do you generate REST service template with wadl2java where POST/PUT methods have parameters?)
  • 我无法理解我的travis构建有什么问题(I am having trouble understanding what is wrong with my travis build)
  • iOS9 Scope Bar出现在Search Bar后面或旁边(iOS9 Scope Bar appears either behind or beside Search Bar)
  • 为什么开机慢上面还显示;Inetrnet,Explorer
  • 有关调用远程WCF服务的超时问题(Timeout Question about Invoking a Remote WCF Service)